package com.study.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 消费者，配置了 确认机制 和 手动发送 ack；多个消费者监听同一个队列，消费者会轮询去消费消息
 *
 * @author huang guang yue
 * @version v1.0.0
 * @date 2020 2020/11/16 17:25
 */
@Component
@RabbitListener(queues = "queue_simple")
public class Consumer1 {

    /**
     * 处理消息
     *
     * @param msg     实际发送的消息体
     * @param channel 信道
     * @param message rabbitmq 的消息体
     */
    @RabbitHandler
    public void handle(String msg, Channel channel, Message message) throws IOException {
        System.out.println("Consumer1 收到消息：" + msg);
        try {
            // 手动发送 ack 即消息确认，如果成功，交换机会删除队列的消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            if (message.getMessageProperties().getRedelivered()) {
                System.out.println("消息重复确认失败，拒绝消息");
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                System.out.println("消息确认失败，消息将再次返回队列");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }
    }
}
